{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "f6b480b258ee"
   },
   "source": [
    "##### Copyright 2022 The Cirq Developers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cellView": "form",
    "id": "906e07f6e562"
   },
   "outputs": [],
   "source": [
    "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#\n",
    "# https://www.apache.org/licenses/LICENSE-2.0\n",
    "#\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "EQvWLKKRgZR9"
   },
   "source": [
    "# Parameter Sweeps"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "EvZ_JecKga2p"
   },
   "source": [
    "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://quantumai.google/cirq/simulate/params\"><img src=\"https://quantumai.google/site-assets/images/buttons/quantumai_logo_1x.png\" />View on QuantumAI</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/quantumlib/Cirq/blob/main/docs/simulate/params.ipynb\"><img src=\"https://quantumai.google/site-assets/images/buttons/colab_logo_1x.png\" />Run in Google Colab</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://github.com/quantumlib/Cirq/blob/main/docs/simulate/params.ipynb\"><img src=\"https://quantumai.google/site-assets/images/buttons/github_logo_1x.png\" />View source on GitHub</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a href=\"https://storage.googleapis.com/tensorflow_docs/Cirq/docs/simulate/params.ipynb\"><img src=\"https://quantumai.google/site-assets/images/buttons/download_icon_1x.png\" />Download notebook</a>\n",
    "  </td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "bd9529db1c0b"
   },
   "outputs": [],
   "source": [
    "try:\n",
    "    import cirq\n",
    "except ImportError:\n",
    "    print(\"installing cirq...\")\n",
    "    !pip install --quiet cirq\n",
    "    print(\"installed cirq.\")\n",
    "    import cirq"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "0e4a50aed04a"
   },
   "source": [
    "## Concept of Circuit Parameterization and Sweeps\n",
    "\n",
    "Suppose you have a quantum circuit and in this circuit there is a gate with some parameter. You might wish to run this circuit for different values of this parameter.  An example of this type of circuit is a Rabi flop experiment. This experiment runs a set of quantum computations which 1) starts in  $|0\\rangle$ state, 2) rotates the state by $\\theta$ about the $x$ axis, i.e. applies the gate $\\exp(i \\theta X)$, and 3) measures the state in the computational basis.  Running this experiment for multiple values of $\\theta$, and plotting the probability of observing a $|1\\rangle$ outcome yields the quintessential $\\cos^2$ probability distribution as a function of the parameter $\\theta$.  To support this type of experiment, Cirq provides the concept of parameterized circuits and parameter sweeps.  \n",
    "\n",
    "The next cell illustrates parameter sweeps with a simple example.  Suppose you want to compare two quantum circuits that are identical except for a single exponentiated `cirq.Z` gate."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "5b7f70e0044a"
   },
   "outputs": [],
   "source": [
    "q0 = cirq.LineQubit(0)\n",
    "\n",
    "circuit1 = cirq.Circuit([cirq.H(q0), cirq.Z(q0) ** 0.5, cirq.H(q0), cirq.measure(q0)])\n",
    "print(f\"circuit1:\\n{circuit1}\")\n",
    "\n",
    "circuit2 = cirq.Circuit([cirq.H(q0), cirq.Z(q0) ** 0.25, cirq.H(q0), cirq.measure(q0)])\n",
    "print(f\"circuit2:\\n{circuit2}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "0bbbafcbd46b"
   },
   "source": [
    "You could run these circuits separately (either on hardware or in simulation), and collect statistics on the results of these circuits. However parameter sweeps can do this in a cleaner and more perfomant manner.  \n",
    "\n",
    "First define a parameter, and construct a circuit that depends on this parameter. Cirq uses [SymPy](https://www.sympy.org/en/index.html){:external}, a symbolic mathematics package, to define parameters. In this example the Sympy parameter is `theta`, which is used to construct a parameterized circuit."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "e3a500a02d00"
   },
   "outputs": [],
   "source": [
    "import sympy\n",
    "\n",
    "theta = sympy.Symbol(\"theta\")\n",
    "\n",
    "circuit = cirq.Circuit([cirq.H(q0), cirq.Z(q0) ** theta, cirq.H(q0), cirq.measure(q0)])\n",
    "print(f\"circuit:\\n{circuit}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "39411f440f90"
   },
   "source": [
    "Notice now that the circuit contains a `cirq.Z` gate that is raised to a power, but this power is the parameter `theta`.  This is a \"parameterized circuit\".  An equivalent way to construct this circuit, where the parameter is actually a parameter in the gate constructor's arguments, is:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "72016524d2b8"
   },
   "outputs": [],
   "source": [
    "circuit = cirq.Circuit(cirq.H(q0), cirq.ZPowGate(exponent=theta)(q0), cirq.H(q0), cirq.measure(q0))\n",
    "print(f\"circuit:\\n{circuit}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "5ee7e4d0795f"
   },
   "source": [
    "Note: You can check whether an object in Cirq is parameterized using `cirq.is_parameterized`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "6a13c552a879"
   },
   "outputs": [],
   "source": [
    "cirq.is_parameterized(circuit)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "83d26b614ffe"
   },
   "source": [
    "Parameterized circuits are just like normal circuits; they just aren't defined in terms of gates that you can actually run on a quantum computer without the additional information about the values of the parameters.  Following the example above, you can generate the two circuits (`circuit1` and `circuit2`) by using `cirq.resolve_parameter` and supplying the values that you want the parameter(s) to take:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "380c37fade59"
   },
   "outputs": [],
   "source": [
    "# circuit1 has theta = 0.5\n",
    "cirq.resolve_parameters(circuit, {\"theta\": 0.5})\n",
    "# circuit2 has theta = 0.25\n",
    "cirq.resolve_parameters(circuit, {\"theta\": 0.25})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "6463c8d810fa"
   },
   "source": [
    "More interestingly, you can combine parameterized circuits with a list of parameter assignments when doing things like running circuits or simulating them.  These lists of parameter assignements are called \"sweeps\".  For example you can use a simulator's `run_sweep` method to run simulations for the parameters corresponding to the two circuits defined above. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "5ad9784a61b5"
   },
   "outputs": [],
   "source": [
    "sim = cirq.Simulator()\n",
    "results = sim.run_sweep(circuit, repetitions=25, params=[{\"theta\": 0.5}, {\"theta\": 0.25}])\n",
    "for result in results:\n",
    "    print(f\"param: {result.params}, result: {result}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "75e583a33046"
   },
   "source": [
    "To recap, you can construct parameterized circuits that depend on parameters that have not yet been assigned a value.  These parameterized circuits can then be resolved to circuits with actual values via a dictionary that maps the sympy variable name to the value that parameter should take. You can also construct lists of dictionaries of parameter assignments, called sweeps, and pass this to many functions in Cirq that use circuits to do an action (such as `simulate` or `run`).  For each of the elements in the sweep, the function will execute using the parameters as described by the element."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "985ff927ebdd"
   },
   "source": [
    "## Constructing Sweeps\n",
    "\n",
    "The previous example constructed a sweep by simply constructing a list of parameter assignments, `[{\"theta\": 0.5}, {\"theta\": 0.25}]`.  Cirq also provides other ways to construct sweeps.  \n",
    "\n",
    "One useful method for constructing parameter sweeps is `cirq.Linspace` which creates a sweep over a list of equally spaced elements.  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "fcf802956766"
   },
   "outputs": [],
   "source": [
    "# Create a sweep over 5 equally spaced values from 0 to 2.5.\n",
    "params = cirq.Linspace(key=\"theta\", start=0, stop=2.5, length=5)\n",
    "for param in params:\n",
    "    print(param)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "e0d86edee975"
   },
   "source": [
    "Note: The `Linspace` sweep is composed of `cirq.ParamResolver` instances instead of simple dictionaries. However, you can think of them as effectively the same for most use cases. \n",
    "\n",
    "If you need to explicitly and individually specify each parameter resolution, you can do it by constructing a list of dictionaries as before. However, you can also use `cirq.Points` to do this more succinctly."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "8371d9c02076"
   },
   "outputs": [],
   "source": [
    "params = cirq.Points(key=\"theta\", points=[0, 1, 3])\n",
    "for param in params:\n",
    "    print(param)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "cd97c725e966"
   },
   "source": [
    "If you're working with parameterized circuits, it is very likely you'll need to keep track of multiple parameters. Two common use cases necessitate building a sweep from two constituent sweeps, where the new sweep includes: \n",
    "- Every possible combination of the elements of each sweep: A cartesian product. \n",
    "- A element-wise pairing of the two sweeps: A zip.\n",
    "\n",
    "The following are examples of using the `*` and `+` operators to combine sweeps by cartesian product and zipping, respectively. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "bd9ace411791"
   },
   "outputs": [],
   "source": [
    "sweep1 = cirq.Linspace(\"theta\", 0, 1, 5)\n",
    "sweep2 = cirq.Points(\"gamma\", [0, 3])\n",
    "# By taking the product of these two sweeps, you can sweep over all possible\n",
    "# combinations of the parameters.\n",
    "for param in sweep1 * sweep2:\n",
    "    print(param)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "c55ea3d1b5ae"
   },
   "outputs": [],
   "source": [
    "sweep1 = cirq.Points(\"theta\", [1, 2, 3])\n",
    "sweep2 = cirq.Points(\"gamma\", [0, 3, 4])\n",
    "# By taking the sum of these two sweeps, you can combine the sweeps\n",
    "# elementwise (similar to python's zip function):\n",
    "for param in sweep1 + sweep2:\n",
    "    print(param)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "b9d5e67f80e5"
   },
   "source": [
    "`cirq.Linspace` and `cirq.Points` are instances of the `cirq.Sweep` class, which explicitly supports cartesian product with the `*` operation, and zipping with the `+` operation. The `*` operation produces a `cirq.Product` object, and `+` produces a `cirq.Zip` object, both of which are also `Sweep`s. Other mathematical operations will not work in general *between sweeps*."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "a3eac1b9cf98"
   },
   "source": [
    "## Symbols and Expressions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "802e8fabd18c"
   },
   "source": [
    "[SymPy](https://www.sympy.org/en/index.html){:external} is a general symbolic mathematics toolset, and you can leverage this in Cirq to define more complex parameters than have been shown so far. For example, you can define an expression in Sympy and use it to construct circuits that depend on this expression:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "54f791f74371"
   },
   "outputs": [],
   "source": [
    "# Construct an expression for 0.5 * a + 0.25:\n",
    "expr = 0.5 * sympy.Symbol(\"a\") + 0.25\n",
    "print(expr)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "2f207f4bc301"
   },
   "outputs": [],
   "source": [
    "# Use the expression in the circuit:\n",
    "circuit = cirq.Circuit(cirq.X(q0) ** expr, cirq.measure(q0))\n",
    "print(f\"circuit:\\n{circuit}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "d6501bf32491"
   },
   "source": [
    "Both the exponents and parameter arguments of circuit operations can in fact be any general Sympy expression: The previous examples just used single-variable expressions. When you resolve parameters for this circuit, the expressions are evaluated under the given assignments to the variables in the expression. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "310b5976c042"
   },
   "outputs": [],
   "source": [
    "print(cirq.resolve_parameters(circuit, {\"a\": 0}))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "3853e96f6abd"
   },
   "source": [
    "Just as before, you can pass a sweep over variable values to `run` or `simulate`, and Cirq will evaluate the expression for each possible value. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "9b36047325eb"
   },
   "outputs": [],
   "source": [
    "sim = cirq.Simulator()\n",
    "results = sim.run_sweep(circuit, repetitions=25, params=cirq.Points('a', [0, 1]))\n",
    "for result in results:\n",
    "    print(f\"param: {result.params}, result: {result}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "dae5c1c38113"
   },
   "source": [
    "Sympy supports a large number of numeric functions and methods, which can be used to create fairly sophisticated expressions, like cosine, exponentiation, and more:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "b5f03870ccf3"
   },
   "outputs": [],
   "source": [
    "print(sympy.cos(sympy.Symbol(\"a\")) ** sympy.Symbol(\"b\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "93ddeb7cee7d"
   },
   "source": [
    "Cirq can numerically evaluate all of the expressions Sympy can evalute. However, if you are running a parameterized circuit on a service (such as on a hardware backed quantum computing service) that service may not support evaluating all expressions. See documentation for the particular service you're using for details. \n",
    "\n",
    "As a general workaround, you can instead use Cirq's flattening ability to evaluate the parameters before sending them off to the service."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "d734d8b4ccdb"
   },
   "source": [
    "### Flattening Expressions\n",
    "\n",
    "Suppose you build a circuit that includes multiple different expressions:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "4a521736bfcd"
   },
   "outputs": [],
   "source": [
    "a = sympy.Symbol('a')\n",
    "circuit = cirq.Circuit(cirq.X(q0) ** (a / 4), cirq.Y(q0) ** (1 - a / 2), cirq.measure(q0))\n",
    "print(circuit)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "a7592df0d861"
   },
   "source": [
    "Flattening replaces every expression in the circuit with a new symbol that is representative of the value of that expression. Additionally, it keeps track of the new symbols and provices a `cirq.ExpressionMap` object to map the old sympy expression objects to the new symbols that replaced them. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "7547e141b34b"
   },
   "outputs": [],
   "source": [
    "# Flatten returns two objects, the circuit with new symbols, and the mapping from old to new values.\n",
    "c_flat, expr_map = cirq.flatten(circuit)\n",
    "print(c_flat)\n",
    "print(expr_map)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "756ad9a92137"
   },
   "source": [
    "Notice that the new circuit has new symbols, `<a/2>` and `<1-a/2>`, which are explicitly not expressions.  You can see this by looking at the value of the exponent in the first gate:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "66a3c56a21e2"
   },
   "outputs": [],
   "source": [
    "first_gate = c_flat[0][q0].gate\n",
    "print(first_gate.exponent)\n",
    "# Note this is a symbol, not an expression\n",
    "print(type(first_gate.exponent))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "3b5a767a93bc"
   },
   "source": [
    "The second object returned by `cirq.flatten` is an object that can be used to map sweeps over the previous symbols to new sweeps over the new expression-symbols. The values assigned to the new expression symbols in the resulting sweep are the old expressions kept track of in the `ExpressionMap`, but resolved with the values provided by the original input sweep."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "09f7a22f32a7"
   },
   "outputs": [],
   "source": [
    "sweep = cirq.Linspace(a, start=0, stop=3, length=4)\n",
    "print(f\"Old {sweep}\")\n",
    "\n",
    "new_sweep = expr_map.transform_sweep(sweep)\n",
    "print(f\"New {new_sweep}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "c560b632e84d"
   },
   "source": [
    "To reinforce: The new sweep is over two new symbols, which each represent the values of the expressions in the original circuit. The values assigned to these new expression symbols is acquired by evaluating the expressions with `a` resolved to a value in `[0, 4]`, according to the old sweep. \n",
    "\n",
    "You can use these new sweep elements to resolve the parameters of the flattened circuit:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "943624f92b80"
   },
   "outputs": [],
   "source": [
    "for params in new_sweep:\n",
    "    print(c_flat, '=>', end=' ')\n",
    "    print(cirq.resolve_parameters(c_flat, params))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "beff46419af0"
   },
   "source": [
    "Using `cirq.flatten`, you can always take a parameterized circuit with any complicated expressions, plus a sweep, and produce an equivalent circuit with no expressions, only symbols, and a sweep for these new symbols. Because this is a common flow, Cirq provides `cirq.flatten_sweep` to do this in one step:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "42384c62a42d"
   },
   "outputs": [],
   "source": [
    "c_flat, new_sweep = cirq.flatten_with_sweep(circuit, sweep)\n",
    "print(c_flat)\n",
    "print(new_sweep)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "9b3f42c586a4"
   },
   "source": [
    "You can then directly use these objects to run the sweeps. For example, you can use them to perform a simulation:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "6c2a38e42993"
   },
   "outputs": [],
   "source": [
    "sim = cirq.Simulator()\n",
    "results = sim.run_sweep(c_flat, repetitions=20, params=new_sweep)\n",
    "for result in results:\n",
    "    print(result.params, result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "de31ae91808b"
   },
   "source": [
    "You can see that the different flattened parameters have corresponding different results for their simulation."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "63FrLKWk9_mC"
   },
   "source": [
    "### Immutability of Sweeps\n",
    "\n",
    "Sweeps and parameter resolvers should be considered immutable objects and should not be modified after creation.\n",
    "\n",
    "Many of these parameter resolvers use dictionaries for internal storage of symbol mappings.  Though dictionaries are mutable in python, users should not modify internal mappings of resolvers after creation.  Doing so may have undesirable and unpredictable results.\n",
    "\n",
    "Instead, create a new dictionary and a new parameter resolver object rather than attempting to modify an existing object."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "48f8502171e3"
   },
   "source": [
    "# Summary\n",
    "\n",
    "- Cirq circuits can handle arbitrary Sympy expressions in place of exponents and parameter arguments in operations.\n",
    "- By providing one or a sequence of `ParamResolver`s or dictionaries that resolve the Sympy variables to values, `run`, `simulate`, and other functions can iterate efficiently over different parameter assignments for otherwise identical circuits. \n",
    "- Sweeps can be created succinctly with `cirq.Points` and `cirq.Linspace`, and composed with each other with `*` and `+`, to create `cirq.Product` and `cirq.Zip` sweeps. \n",
    "- When the service you're using does not support arbitrary expressions, you can flatten a circuit and sweep into a new circuit that doesn't have complex expressions, and a corresponding new sweep. "
   ]
  }
 ],
 "metadata": {
  "colab": {
   "name": "params.ipynb",
   "toc_visible": true
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
